package com.tepth.busfix.main.alarm;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.support.design.widget.TabLayout;
import android.support.graphics.drawable.VectorDrawableCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.tepth.busfix.R;
import com.tepth.busfix.adapter.SimpleFragmentPagerAdapter;
import com.tepth.busfix.base.BaseActivity;
import com.tepth.busfix.base.BaseFragment;
import com.tepth.busfix.bean.reponse.AlarmInfo;
import com.tepth.busfix.bean.reponse.AlarmType;
import com.tepth.busfix.bean.reponse.BusInfo;
import com.tepth.busfix.config.SpKey;
import com.tepth.busfix.main.login.LoginActivity;
import com.tepth.busfix.main.partsearch.PartSearchActivity;
import com.tepth.busfix.tools.SPUtils;
import com.tepth.busfix.view.dialog.DialogDelegate;
import com.tepth.busfix.view.dialog.SweetAlertDialogDelegate;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by zhangyu on 2017/3/21.
 */

public class AlarmInfoActivity extends BaseActivity
        implements AlarmInfoContract.View {
    public static final String EXTRA_NAME = "busInfo";
    public static final String TROUBLE_TYPE_ID = "troubleTypeId";
    public static final String FILTER = "filter";
    private boolean isPortrait = true;


    public static void startActivity(Activity activity, BusInfo busInfo, long typeId, boolean isFilter) {
        Intent intent = new Intent(activity, AlarmInfoActivity.class);
        intent.putExtra(EXTRA_NAME, busInfo);
        intent.putExtra(TROUBLE_TYPE_ID, typeId);
        intent.putExtra(FILTER, isFilter);
        activity.startActivity(intent);
    }

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tabs)
    TabLayout tabLayout;
    @BindView(R.id.viewpager)
    ViewPager viewPager;
    BusInfo busInfo;
    DialogDelegate dialogDelegate;
    SimpleFragmentPagerAdapter fragmentAdapter;
    private List<BaseFragment> listFragments = new ArrayList<>();

    private AlarmInfoPresenter mPresenter;
    private long mTypeId;
    private boolean isFilter = false;

    @Override
    public void onNetworkError(String msg) {
        dialogDelegate.stopProgressWithFailed(msg, msg);
    }

    @Override
    public void onError(String msg) {
        dialogDelegate.stopProgressWithFailed(msg, msg);
    }

    @Override
    public void onTokenInvalid(String msg) {
        dialogDelegate.stopProgressWithWarning(msg, "请重新登录", new DialogDelegate.OnDialogListener() {
            @Override
            public void onClick() {
                Intent intent = new Intent(AlarmInfoActivity.this, LoginActivity.class);
                intent.putExtra("reload", "reload");
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_alarm_info;
    }

    @Override
    public void initView() {
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        initOrientation();
        Intent intent = getIntent();
        busInfo = (BusInfo) intent.getSerializableExtra(EXTRA_NAME);
        mTypeId = intent.getLongExtra(TROUBLE_TYPE_ID, -1);
        isFilter = intent.getBooleanExtra(FILTER, false);
        if (busInfo != null) {
            tvTitle.setText(getString(R.string.bus_number) + busInfo.getVehicleCode() + getString(R.string.alarm_info));
        }
        dialogDelegate = new SweetAlertDialogDelegate(this);
        if (!isFilter) {
            mPresenter.getAlarmInfo();
        } else {
            mPresenter.getAlarmInfoByTroubleTypeId();
        }
        dialogDelegate.showProgressDialog(false, "正在加载...");
    }

    @Override
    public void setPresenter() {
        mPresenter = new AlarmInfoPresenter();
        AlarmInfoModel mModel = new AlarmInfoModel();
        mPresenter.setVM(this, mModel);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return true;
    }

    @Override
    public String getAuthKey() {
        return SPUtils.getString(this, SpKey.KEY_AUTH_KEY, "");
    }

    @Override
    public String getVehicleId() {
        if (busInfo != null) {
            return busInfo.getVehicleId() + "";
        } else {
            return "";
        }
    }

    @Override
    public long getTroubleTypeId() {
        return mTypeId;
    }

    @Override
    public void showAlarmTypes(List<AlarmType> alarmTypes) {
        dialogDelegate.clearDialog();
        try {
            //页面，数据源
            List<View> tabViews = new ArrayList<>();
            for (AlarmType alarmType : alarmTypes) {
                ArrayList<AlarmInfo> alarmInfos = alarmType.getListAlarm();
                listFragments.add(AlarmFragment.newInstance("", alarmInfos, isPortrait));
                View v = LayoutInflater.from(this).inflate(R.layout.view_tab_alarm, null);
                ImageView imageView = (ImageView) v.findViewById(R.id.iv_alarm);
                VectorDrawableCompat drawable = null;
                switch ((int) alarmType.getLevel()) {
                    case 1:
                        drawable = VectorDrawableCompat.create(getResources(), R.drawable.ic_warning_level_3_24dp, getTheme());
                        break;
                    case 2:
                        drawable = VectorDrawableCompat.create(getResources(), R.drawable.ic_warning_level_2_24dp, getTheme());
                        break;
                    case 3:
                        drawable = VectorDrawableCompat.create(getResources(), R.drawable.ic_warning_level_1_24dp, getTheme());
                        break;
                }
                imageView.setImageDrawable(drawable);
                TextView textView = (TextView) v.findViewById(R.id.tv_count);
                textView.setText(
                        "(" + alarmInfos.size() + ")");

                tabViews.add(v);
            }


            fragmentAdapter = new SimpleFragmentPagerAdapter(getSupportFragmentManager(), listFragments);
            viewPager.setAdapter(fragmentAdapter);
            tabLayout.setupWithViewPager(viewPager);

            //设置自定义视图
            for (int i = 0; i < tabLayout.getTabCount(); i++) {
//            BadgeView badgeView = new BadgeView(this);
//            badgeView.setText("10");
//            badgeView.setTargetView(textView);
                TabLayout.Tab tab = tabLayout.getTabAt(i);
                tab.setCustomView(tabViews.get(i));
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "没有相关报警数据!", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        int mCurrentOrientation = getResources().getConfiguration().orientation;

        if (mCurrentOrientation == Configuration.ORIENTATION_PORTRAIT) {
            for (BaseFragment fragment : listFragments) {
                fragment.onChange(true);
            }
        } else {
            for (BaseFragment fragment : listFragments) {
                fragment.onChange(false);
            }
        }
    }

    private void initOrientation() {
        int mCurrentOrientation = getResources().getConfiguration().orientation;
        if (mCurrentOrientation == Configuration.ORIENTATION_PORTRAIT) {
            isPortrait = true;
        } else if (mCurrentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
            isPortrait = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.onDestroy();
    }
}
